<?php
/**
 * 快三开奖。 中奖不在这里
 */
defined('IN_YuLin') || exit('NO PERMIT!');
include_once (ROOT_PATH.'module/lottery/script_common.inc.php');
$beginTime = time();
if ($beginTime < strtotime(date('Y-m-d ') . '00:05:00') || $beginTime > strtotime(date('Y-m-d ') . '23:59:59')) return;

echo '<pre>';
// 获取十一选五需要计算开奖的所有彩种信息
$creditPlayTab = Table('lottery_credit_play');
$lottTab       = Table('lottery');
$cateTab       = Table('lottery_category');
$qihaoTab      = Table('lottery_k3');
// 获取当前 十一选五需要计算的彩种
$sql = 'SELECT lott.`id`, lott.`title`, lott.`credit`, play.`open_param`, play.`type_id` FROM ' . $creditPlayTab . ' AS play
        LEFT JOIN ' . $lottTab . ' AS lott
        ON play.`lott_id` = lott.`id`
        LEFT JOIN ' . $cateTab . ' AS cate
        ON cate.`id` = lott.`cate_id`
        WHERE cate.`sname` = "k3" AND lott.`credit` = 1 AND play.status = 1';
$lottList       = $db->getall($sql);

foreach ($lottList as $lk => $lv){
// 获取当前彩种的期号信息， 准备计算
//     $sql    = 'SELECT id, `code`, `stoptime` FROM ' . $qihaoTab . ' WHERE tid = ' . $lv['id'] . ' AND `code` is null AND `day` = ' . date('Ymd') . ' ORDER BY id ASC limit 1';
    $sql    = 'SELECT id, tid, period, starttime, stoptime, day, opentime, `code` FROM ' . $qihaoTab . ' WHERE tid = ' . $lv['id'] . ' AND stoptime < ' . $beginTime. ' ORDER BY starttime DESC limit 1';
    $qihaoInfo = $db->getrow($sql);
    // 如果已开奖，则跳过， 或者还没到时间
    if ($qihaoInfo['code'] || !$qihaoInfo || $qihaoInfo['stoptime'] > $beginTime) continue;
    
    if ($lv['type_id'] == 2){
        // 获取指定彩种上一期的开彩号码
        $shangqiSql    = 'SELECT `code` FROM ' . $qihaoTab . ' WHERE tid = ' . trim($lv['open_param']) . ' AND `code` != "" ORDER BY starttime DESC limit 1';
        $shangqiInfo   = $db->getrow($shangqiSql);
        if (!$shangqiInfo['code'] || !$shangqiInfo) break;
        
        $rd       = rand(1, 6);
        $lastCode = explode(',', $shangqiInfo['code']);
        $tmpCode  = array();
        foreach ($lastCode as $lk => $lv){
            $lv   = substr(intval($lv * $rd), -1);
            // 计算结果时出现    6*5  or  5*6  结果等于0，  然后开奖号中，该位置就一直是0了， 这里补偿判断
            if (!$lv) $lv = rand(1, 6);
            while($lv > 6){
                $lv = $lv - 6;
            }
            array_push($tmpCode, $lv);
        }
        setOpenCode($qihaoInfo['id'], implode(',', $tmpCode), $db);
        // 计算完毕，跳过下面
        continue;
    }
    
    // 获取当前期号后， 根据期号的id来获取所有当前彩种期号的投注项
    $allBetSql = 'SELECT betting_no, en_play, betting_str, num, multiple, odds, money_unit, eo_money FROM ' . Table('lottery_order_item') . ' WHERE period_id = ' . $qihaoInfo['id'];
    $allBetList        = $db->getall($allBetSql);
    // 计算总投注金额
    $betAmountSql = 'SELECT sum(money) as bet_amount FROM ' . Table('lottery_order_item') . ' WHERE period_id = ' . $qihaoInfo['id'];
    $betAmount    = $db->getrow($betAmountSql);
    // 总投注 * 后台设置百分比（intval后成整数了） * 0.01
    $winnerMax    = $betAmount['bet_amount'] * intval($lv['open_param']) * 0.01;
    // ==========================================================================================================
    // ========================== 计算开奖部分 ===================================================================
    // 投注总金额小于10000， 则随机计算一个都不中奖的号码
    if ($betAmount['bet_amount'] < 10000 || !$allBetList || empty($allBetList)){
        // 投注金额太少，直接随机一个开奖号码
        $openCode = array(rand(1, 6), rand(1, 6), rand(1, 6));
        setOpenCode($qihaoInfo['id'], implode(',', $openCode), $db);
        continue;
    }
    // 模拟中奖号码
    $winnerTest = array();
    for($i = 1; $i <= 6; $i++){
        for($i1 = 1; $i1 <= 6; $i1++){
            for($i2 = 1; $i2 <= 6; $i2++){
                $winnerAmount = 0;
                $key = $i . '-' . $i1 . '-' . $i2;
                foreach ($allBetList as $ak => $av){
                    $flag = checkZhongjiang($av, array($i, $i1, $i2));
                    if ($flag){
                        $winnerAmount += $av['num'] * $av['multiple'] * $av['odds'] * $av['money_unit'] * $av['eo_money'];
                    }
                }
                $winnerTest[$key] = $winnerAmount;
                if ($winnerAmount > $winnerMax) break;
            }
        }
    }
    
    arsort($winnerTest);
    $setStatus = 0;
    $tmpCode   = '';
    foreach ($winnerTest as $ok => $ov){
        if ($ov < $winnerMax) {
            $setStatus = 1;
            $tmpCode   = implode(',', $ok);
            setOpenCode($qihaoInfo['id'], $tmpCode, $db);
            break;
        }
    }
    if (!$setStatus){
        // 如果所有号码投注返奖都比设定值大， 那么用最少中奖的开奖号码写进去。（理论上不会运气这么棒，走到这里来）$ok 为上面循环结束后的最后一次赋值，最少中奖开奖号码
        setOpenCode($qihaoInfo['id'], $ok, $db);
    }
}
print_r($winnerTest);

/**
 * 检查投注项是否中奖
 * @param $data : 投注内容
 * @param $kaijiang : 开奖结果
 * @param $db   : 数据库连接对象
 */
function checkZhongjiang($data, $kaijiang, $db){
    $flag  = false;
    $bet   = $data['betting_no'];

    switch ($data['en_play']){
        case 'HE':
            $sum  = array_sum($kaijiang['code_arr']);
            $dx   = '小';
            $ds   = '双';
            if ($sum > 10) $dx = '大';
            if ($sum % 2) $ds  = '单';
            if ($bet == $dx || $bet == $ds || $bet == $sum) $flag  = true;
            break;
        case 'STHTX':
            $flag  = true;
            $first = array_shift($kaijiang['code_arr']);
            foreach ($kaijiang['code_arr'] as $k => $v){
                if ($v != $first){
                    $flag = false;
                    break;
                }else{
                    $flag = true;
                }
            }
            break;
        case 'STHDX':
            if (implode('', $kaijiang['code_arr']) == $bet) $flag  = true;
            break;
        case 'SBTH':
            if (str_replace(',', '', $bet) == implode(',', $kaijiang['code_arr'])) $flag  = true;
            break;
        case 'SLHTX':
            $first = array_shift($kaijiang['code_arr']);
            if ($first == ($kaijiang['code_arr'][1] - 1) && $first == ($kaijiang['code_arr'][2] - 2)) $flag  = true;
            break;
        case 'ETHFX':
        case 'EBTH':
            $flag  = true;
            for($i = 0; $i < strlen($bet); $i++){
                if(!in_array(substr($bet, $i, 1), $kaijiang['code_arr'])) {
                    $flag = false;
                    break;
                }
            }
            if ($flag) $update['winner'] = 2;
            break;
        case 'ETHDX':
            if(str_replace(',', '', $bet) == implode('', $kaijiang['code_arr'])) $update['winner'] = 2;
            break;
    }
    return $flag;
}
echo 'end';
